<?php


namespace App\Repositories\Seller;


use App\Models\GoodsType;
use App\Repositories\BaseRepository;
use Illuminate\Database\Eloquent\Model;

class GoodsTypeRepository extends BaseRepository
{

    /**
     * @return Model
     */
    public function model()
    {
        return new GoodsType();
    }

    public function create(array $data)
    {
        return $this->model()->create($data);
    }

    public function tree($where = [], $param = [])
    {
        $parent_id = $param['parent_id'] ?? 0;
        $data = $this->model()->where($where)->orderBy('sort', 'desc')->get();
        if ($data) {
            return getTree($data->toArray(), $parent_id);
        } else {
            return [];
        }
    }

    public function selectTree($seller_id, $only_parent = false)
    {
        $where['seller_id'] = $seller_id;
        if ($only_parent) {
            $where['is_parent'] = true;
        }
        $data = $this->model()->where($where)->orderBy('sort', 'desc')->select([
            'name as label',
            'parent_id',
            'id as value',
            'is_parent'
        ])->get();
        foreach ($data as &$value) {
            $value['value'] = (string)$value['value'];
        }
        if ($data) {
            $tree = getTree($data->toArray(), 0, 'parent_id', 'children', 'value');
            return $tree;
        } else {
            return [];
        }

    }

}